<?php

namespace app\common\common\Server;


use app\common\common\model\oldModel\member\member;
use app\common\common\model\member\member as newMember;


use app\common\common\model\oldModel\store\Store as oldStore;
use app\common\common\model\order\fromId;
use app\common\common\model\oldModel\order\order;
use app\common\common\model\oldModel\order\OrderItem;
use app\common\common\Server\commonServer;
use app\common\common\model\oldModel\member\memberScore;

/**
 * 小程序模板消息推送接口
 */
class TemplateMessageServer
{


    /**
     * 通过旧用户获取新用户的信息
     * 先找unionid，然后才用手机号码获取用户
     * @param $new_mid
     * @return array|bool|false|\PDOStatement|string|\think\Model
     */
    public function getOldMemberByNewId($old_mid){
        $old_member_field = (new member())->findByWhere(['member_id'=>$old_mid]);

        if(empty($old_member_field)){
            return false;
        }
        $member_model = new newMember();
        //通过UnionID 查找用户，
        $member_field = $member_model->findByWhere(['union_id'=> $old_member_field['union_id']]);


        //如果不存在用手机号码兜底
        if(empty($member_field) && isset($old_member_field['phone'])){
            $member_field = $member_model->findByWhere(['mobile'=>$old_member_field['phone']]);
        }
        if(empty($member_field)){
            return false;
        }
        return $member_field;
    }

    public  function sendMessage($order_code,$type_send){
        aw_log('获取参数5'.$order_code.'_'.$type_send ,'canxingjian3.log');
        if(empty($type_send) || empty($order_code) ){
            return false;
        }

        sleep(3);//延时执行
        $res_data = [];
        $arr_data = [];
        //获取订单
        $order = new order();
        $order_map['order_code'] = $order_code;
        $find_order_data = $order->findByWhere($order_map);
        //aw_log('获取订单数据6'.json_encode($find_order_data) ,'canxingjian3.log');

        $arr_data['order_code'] = $find_order_data['order_code'];
        $arr_data['refund_money'] = !empty($find_order_data['refund_money'])?$find_order_data['refund_money']:0.00;
        $arr_data['order_id'] = $find_order_data['order_id'];
        $arr_data['money_pay'] = $find_order_data['money_pay'];
        $arr_data['table_num'] = $find_order_data['table_num'];
        $arr_data['create_time'] = $find_order_data['create_time'];

        //获取店面信息
        $oldStore = new oldStore();
        $store_map['store_id'] = $find_order_data['store_id'];
        $find_store_data = $oldStore->findByWhere($store_map);
        $arr_data['store_name'] = $find_store_data['sname'];

        //查找订单详情信息
        $order_detail = new OrderItem();
        $order_detail_map['order_id'] = $find_order_data['order_id'];
        $all_order_detail = $order_detail->allByWhere($order_detail_map);

        //将订单详情商品名称转换为字符串
        $arr_data['good_names'] = implode(',',array_column($all_order_detail,'goods_name'));

        //支付方式;
        $arr_data['pay_type_name'] = config('pay.order_pay_type')[$find_order_data['pay_type']];
        //aw_log('获取数据7'.json_encode($arr_data) ,'canxingjian3.log');
        //通过旧用户member_id获取到新的member_id
        $new_find_member = $this->getOldMemberByNewId($find_order_data['member_id']);
        //aw_log('获取新的用户8'.json_encode($new_find_member) ,'canxingjian3.log');

        //获取新用户推送fromID
        $fromId = new fromId();
        $fromId_map['user_id'] = $new_find_member['id'];
        $fromId_map['status'] = 1;
        $fromId_map['form_id'] = array('neq','the formId is a mock one');
        $find_fromId_data = $fromId->findBywhereTime($fromId_map);
        aw_log('获取推送数据9'.json_encode($find_fromId_data) ,'canxingjian3.log');
        if(empty($find_fromId_data)){
            $res_data['errcode'] = -1;
            $res_data['errmsg'] = '没有可用的formId';
            return $res_data;
        }

        switch ($type_send){

            case 1: //退款通知

                //查找退款积分变动
                $memberScore = new memberScore();
                $memberScore_map['data'] = $find_order_data['order_id'];
                $memberScore_map['type'] = 3; //退款减积分
                $find_memberScore = $memberScore->findByWhere($memberScore_map);
                //aw_log('退款数据5'.json_encode($find_memberScore) ,'canxingjian3.log');
                $arr_data['score'] = !empty($find_memberScore['score'])?$find_memberScore['score']:0;//扣除积分
                $arr_data['end_score'] = !empty($find_memberScore['end_score'])?$find_memberScore['end_score']:0; //变动之后积分
                //aw_log('退款数据3'.json_encode($arr_data) ,'canxingjian3.log');
                $dTemplateInfo = $this->getTemplateData($type_send,$arr_data);

                $res = $this->sendTemplate($find_fromId_data['open_id'],$find_fromId_data['form_id'],REFUND_NOTICE,
                    $dTemplateInfo['pages'],$dTemplateInfo['template']);


                if($res['errmsg'] == 'ok'){
                    $fromId->updateWhere(['id' => $find_fromId_data['id']],['status' => 2]);
                    $res_data['errcode'] = 0;
                    $res_data['errmsg'] = $res['errmsg'];
                }else{
                    $res_data['errcode'] = $res['errcode'];
                    $res_data['errmsg'] = $res['errmsg'];
                }
            break;
            case 2: //交易成功通知

                $dTemplateInfo = $this->getTemplateData($type_send,$arr_data);

                $res = $this->sendTemplate($find_fromId_data['open_id'],$find_fromId_data['form_id'],ORDER_PAYMENT_NOTICE,
                    $dTemplateInfo['pages'],$dTemplateInfo['template']);


                if($res['errmsg'] == 'ok'){

                    $fromId->updateWhere(['id' => $find_fromId_data['id']],['status' => 2]);

                    $res_data['errcode'] = 0;
                    $res_data['errmsg'] = $res['errmsg'];
                }else{
                    $res_data['errcode'] = $res['errcode'];
                    $res_data['errmsg'] = $res['errmsg'];
                }
            break;
            case 3: //用户评价通知
                //aw_log('我是评价10' ,'canxingjian2.log');
                $dTemplateInfo = $this->getTemplateData($type_send,$arr_data);
                $res = $this->sendTemplate($find_fromId_data['open_id'],$find_fromId_data['form_id'],ORDER_EVAlLUATION_NOTICE,
                    $dTemplateInfo['pages'],$dTemplateInfo['template']);
                //aw_log('返回数据11-'.json_encode($res),'canxingjian2.log');

                if($res['errmsg'] == 'ok'){
                    $fromId->updateWhere(['id' => $find_fromId_data['id']],['status' => 2]);
                    $res_data['errcode'] = 0;
                    $res_data['errmsg'] = $res['errmsg'];

                }else{
                    $res_data['errcode'] = $res['errcode'];
                    $res_data['errmsg'] = $res['errmsg'];
                }
            break;
            default:
                $res_data['errcode'] = '-1';
                $res_data['errmsg'] = '异常通知';

        }
        return $res_data;


    }

    /**
     * 发送模板消息
     * @param $openID
     * @param $templateid
     * @param $page
     * @param $formid
     * @param $data
     * @param $type
     */
    function sendTemplate($openID,$formid,$templateid,$page='',$data = []){
        $accessToken = getAccessToken();

        $param = [
            'msgtype'=> 'news',
            'template_id'=>$templateid,
            'touser'=>$openID,
            'page'=>$page,
            'form_id'=>$formid,
            'data'=> $data
        ];
        $param = json_encode($param,JSON_UNESCAPED_UNICODE);
        $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$accessToken;
        $result = httpPost($url,$param);
        //@file_put_contents("pangyongfu.log","服务消息返回数据：".$result."\r\n",FILE_APPEND);
        $log['data'] = $data;
        $log['res'] = "服务消息返回数据：".$result;
        aw_log($log,'message_stend2.log');
        $arr = json_decode($result,true);
        return $arr;
    }

    /**
     * 获取模板信息和跳转地址
     * @param $template_id
     * @param $orderInfo
     * @return mixed
     */
    private function getTemplateData($type_send,$orderInfo){
        switch($type_send){
            //退款通知
            case 1 :
                $msg['keyword1'] = ['value'=>$orderInfo['order_code']];
                $msg['keyword2'] = ['value'=>$orderInfo['refund_money']];
                $msg['keyword3'] = ['value'=>$orderInfo['store_name']];
                if(!empty($orderInfo['score'])){
                    $msg['keyword4'] = ['value'=>'-'.$orderInfo['score']];
                }else{
                    $msg['keyword4'] = ['value'=>0];
                }

                $msg['keyword5'] = ['value'=>"感谢您的参与！"];
                $pages = "/pages/orderItem/orderitem?order_id=".$orderInfo['order_id'];
                break;
            //交易成功通知
            case 2 :
                $msg['keyword1'] = ['value'=>$orderInfo['pay_type_name']];
                $msg['keyword2'] = ['value'=>$orderInfo['money_pay']];
                $msg['keyword3'] = ['value'=>$orderInfo['store_name']];
                $msg['keyword4'] = ['value'=>$orderInfo['table_num']];
                $msg['keyword5'] = ['value'=>$orderInfo['create_time']];
                $msg['keyword6'] = ['value'=>"恭喜您下单成功，点击查看订单详情"];
                $pages = "/pages/orderItem/orderitem?order_id=".$orderInfo['order_id'];
                 break;
            //用户评价通知
            case 3 :
                $msg['keyword1'] = ['value'=>$orderInfo['good_names']];
                $msg['keyword2'] = ['value'=>$orderInfo['store_name']];
                $msg['keyword3'] = ['value'=>$orderInfo['create_time']];
                $msg['keyword4'] = ['value'=>"给我们一些建议吧，您的建议是对我们最大的支持。"];
                $pages = "/pages/orderItem/orderitem?order_id=".$orderInfo['order_id'];
                break;
        }
        $data['template'] = $msg;
        $data['pages'] = $pages;
        return $data;
    }



}
